var CACHE_TIME = 60 * 60 * 24 * 365,
  mmieConf;

/**
 * require本模块需要的Node.js模块
 */
var sys = require('util'),
  http = require('http'),
  fs = require('fs'),
  url = require('url'),
  path = require('path');
mmieConf = getMmieConf();

var util = require('util');

exports.getStaticFile = function(pathname, res, req) {
  //var pointPosition = pathname.lastIndexOf('.'),mimeString = pathname.substring(pointPosition + 1),
  var extname = path.extname(pathname); // '.css'
  // console.log(extname.substr(1) + ':' + extname.substring(1) + ':' + extname.slice(1)); // 'css:css:css'
  extname = extname ? extname.slice(1) : '';
  var readPath = STATIC + pathname;
  var mmieType = mmieConf[extname] ? mmieConf[extname] : 'text/plain';
  fs.exists(readPath, function(exists) {
    if (!exists) {
      res.writeHead(404, { 'Content-Type': 'text/plain' });
      res.write('This request URL ' + pathname + ' was not found on this server!');
      res.end();
    } else {
      var fileInfo = fs.statSync(readPath);
      console.log('fileInfo:' + fileInfo);
      var lastModified = fileInfo.mtime.toUTCString();
      console.log('lastModified:' + lastModified);
      if (mmieConf[extname]) {
        var date = new Date();
        date.setTime(date.getTime() + CACHE_TIME * 1000);
        res.setHeader('Expires', date.toUTCString());
        res.setHeader('Cache-Control', 'max-age=' + CACHE_TIME);
      }
      console.log('res:' + util.inspect(res));
      console.log('req:' + util.inspect(req));
      if (req.headers['if-modified-since'] && lastModified == req.headers['if-modified-since']) {
        res.writeHead(304, 'Not Modified');
        res.end();
      } else {
        fs.readFile(readPath, 'binary', function(err, file) {
          if (err) {
            res.writeHead(500, { 'Content-Type': 'text/plain' });
            res.end(err);
          }
          res.setHeader('Last-Modified', lastModified);
          res.writeHead(200, { 'Content-Type': mmieType });
          res.write(file, 'binary');
          res.end();
        });
      }
    }
  });
};

function getMmieConf() {
  var readPath = CONF + '/mmie_type.json';
  var mmieStr = fs.readFileSync(readPath);
  var mmieObj = JSON.parse(mmieStr);
  return mmieObj;
}
